import { Component, OnInit } from "@angular/core";
import { Router, NavigationEnd, NavigationStart, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
//引入用到的rxjs 方法及操作符
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { Observable } from 'rxjs/Observable';
//引入环境变量，用于链接webSocket
import { environment } from '../../environments/environment';
//引入消息、确定、全局储存、socke、登录、服务
import { MessageService } from '../components/common/messageservice';
import { ConfirmationService } from '../components/common/confirmationservice';
import { StorageService } from "../common/storage.service";
import { SocketmessageService } from "../common/socketmessage.service";
import { LoginService } from "../login/login.service";
import { SaasService } from "./saas.service";
import { $WebSocket, WebSocketSendMode } from '../common/websocket.service';
//引入动画
import { flyOut, collapsed, expand } from "../common/animate.common";
//引入全局常量
import { SIDE_BAR_BIG, SIDE_BARS_MALL, NAV_HEIGHT } from "../common/common-config"

@Component({
    templateUrl: './saas.component.html',
    styleUrls: ['./saas.component.css'],
    providers: [StorageService, SocketmessageService],
    animations: [flyOut, collapsed, expand]
})

export class SaasComponent {

    public ws: any;

    small: boolean = true;// 侧边栏缩放 状态

    msgs: any[] = [];//消息提示 新线索 消息组
    messages: any[] = [];//websocket消息提示

    items: any[];//菜单数组

    itemsStatus: any[];

    sidebarWidth: string = SIDE_BARS_MALL;//侧边栏宽度

    navHeight: string = NAV_HEIGHT;//侧边栏宽度

    hasSidebar: boolean; // 隐藏左侧菜单

    hasHeader: boolean; // 隐藏顶部菜单

    showBtn: boolean = false;//登出

    userType: any;// 用户类型

    mobile: any;

    name: string; //名称

    userTypeCode: string;

    iconUrl: string = undefined;

    private localStorage = window.localStorage;

    constructor(private makesure: ConfirmationService, private socket: SocketmessageService, private storage: StorageService, private messageServe: MessageService, private router: Router, private titleService: Title, private activatedRoute: ActivatedRoute, private service: LoginService, private saasService: SaasService) {
        this.creatComponentMessage();
        this.setBrowserTitle();
    };

    ngOnInit() {
        this.storage.getRights().then(data => {
            // this.creatWs(data.userInfo.code); //请求websokket
            //this.creatAuditWs(data.userInfo.code);
            this.getUserInfo(data);
            this.items = data.menu;
        })
    }


    /* 菜单fun  -------start */
    getItem(key): any {
        if (!this.itemsStatus) { this.itemsStatus = this.items };
        this.itemsStatus = this.itemsStatus.find(val => val.path == key);
        return this.itemsStatus
    }

    toggle() {
        this.small = !this.small;
        this.sidebarWidth = this.small ? SIDE_BARS_MALL : SIDE_BAR_BIG
        this.storage.eventbus.emit({ size: this.small, sidebarWidth: this.sidebarWidth});
    }

    /* 菜单fun  -------end */



    /* 个人中心  ------start*/

    getUserInfo(data) {
        //this.userType = this.storage.dicFilter('user_type', data.userInfo.userType);
        let reg = /^(\d{3})\d{4}(\d{4})$/;
        this.mobile = data.userInfo.mobile.replace(reg, "$1****$2");
        this.userTypeCode = data.userTypeCode;
        this.iconUrl = data.userInfo.iconUrl || '/assets/imgs/defaultIcon.png';
        this.name = data.userInfo.fullName
    }

    logoutShow() {
        this.showBtn = !this.showBtn;
    }

    logout() {
        this.service.logout().then(data => {
            if (data.result) {
                this.router.navigateByUrl('login');
                this.ws.close(true);
                this.localStorage.removeItem('rights');
                this.localStorage.removeItem('dic');
                this.localStorage.removeItem('channels');
                this.service.redirectUrl = ''
            } else {
                this.storage.messageService.emit({ severity: 'error', detail: data.msg })
            }
        })
    }
    /* 个人中心         ------end*/






    /* 修改浏览器title  ------start*/
    setBrowserTitle() {
        this.router.events
            .filter(event => {
                if (event instanceof NavigationStart) {
                    console.time('路由切换耗时')
                } else if (event instanceof NavigationEnd) {
                    console.timeEnd('路由切换耗时')
                }
                return event instanceof NavigationEnd
            })
            .map(() => this.activatedRoute)
            .map(route => {
                while (route.firstChild) route = route.firstChild;
                return route;
            })
            .filter(route => route.outlet === 'primary')
            .mergeMap(route => route.data)
            .subscribe((event) => {
                this.hasSidebar = true;
                this.hasHeader = true;
                this.navHeight = NAV_HEIGHT;
                this.sidebarWidth = this.small ? SIDE_BARS_MALL : SIDE_BAR_BIG
                if (event.hasSidebar == false) {
                    this.hasSidebar = false;
                    this.sidebarWidth = '0px';
                }
                if (event.hasHeader == false) {
                    this.hasHeader = false;
                    this.navHeight = '0px';
                }
                this.titleService.setTitle(event['title'])
            });
    }
    /* 修改浏览器title  ------end*/




    /* 组件消息时间  -------start*/

    creatComponentMessage() {
        //消息服务事件
        this.storage.messageService.subscribe(val => {
            this.messageServe.clear();
            this.messageServe.add(val);
        })
        this.storage.userinfoService.subscribe(val => {
            for (let k in val) {
                this[k] = val[k]
            }
        })
        //弹窗 提示 事件
        this.storage.makesureService.subscribe(val => {
            this.makesure.confirm(val)
        })
    }

    /* 组件消息时间  -------enf*/





    /* 链接socket  -----start*/
    /*
        creatAuditWs(code){
    
            if(!code){return}
    
            this.ws = new $WebSocket("ws://172.16.10.157:30001/ws?code=" + code);
    
            this.ws.onMessage(
                (msg: MessageEvent)=> {
                    console.log("123");
                    console.log(msg);
                    let data = JSON.parse(msg.data);
                    if (data.type == "0"){
                        this.newClue(msg.data)
                        this.socket.onMessage.emit(msg.data)
                    }
                },
                {autoApply: false}
            );
    
            this.ws.onOpen(msg=>this.socket.onOpen.emit());
    
            this.ws.onClose(msg=>{this.socket.onClose.emit();console.log(msg)});
    
            this.ws.onError(msg=>this.socket.onError.emit());
    
        }
        */

    /* 链接socket  -----end*/
    newClue2(data) {
        let msg: any = JSON.parse(data);
        msg.onlyContent = true;
        msg.content = msg.msg;
        msg.showClose = true;;
        msg.rejectLabel = '';
        //msg.acceptLabel="查看"
        //this.audit(data);

        this.msgs = [...this.msgs, msg]
    }

    newClue3(data) {
        let msg: any = JSON.parse(data);
        msg.onlyContent = true;
        msg.content = msg.msg;
        msg.showClose = true;
        msg.rejectLabel = '';
        //msg.acceptLabel="查看"
        //this.audit(data);

        this.msgs = [...this.msgs, msg]
    }


    /* 新线索提示 -------start */

    newClue(data) {
        let msg: any = JSON.parse(data);
        let message: any = {};
        message.type = "0";
        message.data = msg;
        if (msg.msgType == "time") {
            message.title = "新线索";
            message.showClose = false;
            message.leftBtnLabel = "接收";
            message.rightBtnLabel = "拒绝";
            message.closeWhenRightClick = true;
            message.closeWhenLeftClick = true;
            message.timeNum = msg.timeNum;
            message.content = [
                { title: "线索编号", content: msg.data.clueCode },
                { title: "线索名称", content: msg.data.clueName }
            ]
        } else if (msg.msgType == "normal") {
            message.title = msg.title;
            message.showClose = true;
            message.leftBtnLabel = "详情";
            message.rightBtnLabel = "拨打电话";
            message.closeWhenRightClick = true;
            message.closeWhenLeftClick = true;
            message.content = [
                { title: "线索编号", content: msg.data.clueCode },
                { title: "线索名称", content: msg.data.clueName }
            ]
        } else if (msg.msgType == "clueFollowupRemind") {
            message.title = msg.title;
            message.showClose = true;
            message.leftBtnLabel = "详情";
            message.rightBtnLabel = "拨打电话";
            message.closeWhenRightClick = true;
            message.closeWhenLeftClick = true;
            message.content = [
                { title: "线索编号", content: msg.data.clueCode },
                { title: "线索名称", content: msg.data.clueName },
                { title: "计划跟进时间", content: msg.data.planDate }
            ]
        } else if (msg.msgType == "business") {
            message.title = msg.title;
            message.showClose = true;
            message.leftBtnLabel = "详情";
            message.rightBtnLabel = "拨打电话";
            message.closeWhenRightClick = true;
            message.closeWhenLeftClick = true;
            message.content = [
                { title: "商机编号", content: msg.data.businCode },
                { title: "商机名称", content: msg.data.businName }
            ]
        } else if (msg.msgType == "businessFollowupRemind") {
            message.title = msg.title;
            message.showClose = true;
            message.leftBtnLabel = "详情";
            message.rightBtnLabel = "拨打电话";
            message.closeWhenRightClick = true;
            message.closeWhenLeftClick = true;
            message.content = [
                { title: "商机编号", content: msg.data.businCode },
                { title: "商机名称", content: msg.data.businName },
                { title: "计划跟进时间", content: msg.data.planDate }
            ]
        } else if (msg.msgType == "exceptionStop") {
            message.title = msg.title;
            message.showClose = true;
            message.leftBtnLabel = "详情";
            message.rightBtnLabel = "";
            message.closeWhenRightClick = true;
            message.closeWhenLeftClick = true;
            message.content = [
                { title: "商机编号", content: msg.data.businCode },
                { title: "商机名称", content: msg.data.businName }
            ]
        }
        console.log(message);
        this.messages = [...this.messages, message]
        /*let msg:any = JSON.parse(data);
        if (msg.msgType != "time"){
          msg.showClose = true;
        }
        msg.rejectLabel = "拒绝";
        console.log(msg);
        //this.audit(data);

       this.msgs = [...this.msgs,msg]*/
    }
    addNewClue(data) {

    }


    /* 新线索提示 -------start */

    // 账号设置
    setting() {
        this.router.navigate(['/saas/account']);
    }

    close(event) {
        console.log('新线索提示关闭');
        console.log(event);
        this.saasService.expireCluei(event);
        //this.removeMsgByCode(event.data.clueCode);
    }

    removeMsgByCode(code) {
        for (let i = this.msgs.length - 1; i >= 0; i--) {
            if (this.msgs[i].data.clueCode == code) {
                this.msgs.splice(i, 1);
                return;
            }
        }
    }

    reject(event) {
        console.log('拒绝新线索');
        console.log(event);
        if (event.type == "0") {
            if (event.msgType == "time") {
                this.saasService.refuseClue(event).then(data => {
                    if (data.result) {
                        this.storage.messageService.emit({ severity: 'success', detail: "操作成功！" });
                    } else {
                        this.storage.messageService.emit({ severity: 'success', detail: data.msg });
                    }
                }
                );
            }
        }
    }

    onClose(event, i) {
        if (event.type == "0") {
            if (event.data.msgType == "time") {
                this.saasService.expireCluei(event);
            }
        }
        this.messages.splice(i, 1);
    }

    onLeftBtnClick(event) {
        if (event.type == "0") {
            if (event.data.msgType == "normal" || event.data.msgType == "clueFollowupRemind") {
                window.open("/saas/clue/myclue/detailclue;id=" + event.data.data.clueCode);
            } else if (event.data.msgType == "time") {
                this.saasService.acceptClue(event).then(data => {
                    if (data.result) {
                        this.storage.messageService.emit({ severity: 'success', detail: "操作成功！" });
                    } else {
                        this.storage.messageService.emit({ severity: 'success', detail: data.msg });
                    }
                }
                );
            } else if (event.data.msgType == "business" || event.data.msgType == "exceptionStop" || event.data.msgType == "businessFollowupRemind") {
                window.open("/saas/business/management/mybusiness-detail;code=" + event.data.data.businCode);
            }
        }
    }

    onRightBtnClick(event) {
        if (event.type == "0") {
            console.log(event)
            if (event.data.msgType == "normal" || event.data.msgType == "clueFollowupRemind") {
                this.saasService.seeClues({ 'clueCode': event.data.data.clueCode }).then(res => {
                    if (res.result) {
                        let phone = {
                            phone: res.data.phone, // 当前线索手机号
                            actionID: event.data.data.clueCode // 当前线索编号
                        }
                        this.saasService.dialingClueKf(phone).then(resDh => {
                            if (resDh.result) {
                                this.storage.messageService.emit({ severity: 'success', detail: '操作成功！请关注七陌平台外呼情况！' })
                                // let timer: NodeJS.Timer = setTimeout(_=> { window.open("/saas/clue/myclue/detailclue;id=" + event.data.data.clueCode);clearTimeout(timer)}, 1000)
                            } else {
                                this.storage.messageService.emit({ severity: 'error', detail: resDh.msg });
                            }
                        }
                        );
                    } else {
                        this.storage.messageService.emit({ severity: 'error', detail: res.msg });
                    }
                }
                );
            } else if (event.data.msgType == "time") {
                this.saasService.acceptClue(event).then(data => {
                    if (data.result) {
                        this.storage.messageService.emit({ severity: 'success', detail: "操作成功！" });
                    } else {
                        this.storage.messageService.emit({ severity: 'error', detail: data.msg });
                    }
                }
                );
            } else if (event.data.msgType == "business" || event.data.msgType == "businessFollowupRemind") {
                this.saasService.myBusinessDetail({ 'businessCode':  event.data.data.businCode }).then(res => {
                    if (res.result) {
                        let phone = {
                            phone: res.data.customer[0].phone, // 当前商机手机号
                            actionID:  event.data.data.businCode // 当前商机编号
                        }
                        this.saasService.dialingBusKf(phone).then(resDh => {
                            if (resDh.result) {
                                this.storage.messageService.emit({ severity: 'success', detail: '操作成功！请关注七陌平台外呼情况！' })
                                // let timer: NodeJS.Timer = setTimeout(_=> { window.open("/saas/business/management/mybusiness-detail;code=" + event.data.data.businCode);clearTimeout(timer)}, 1000)
                            } else {
                                this.storage.messageService.emit({ severity: 'error', detail: resDh.msg });
                            }
                        }
                        );
                    } else {
                        this.storage.messageService.emit({ severity: 'error', detail: res.msg });
                    }
                }
                );
            }
        }
    }

    accept(event) {
        console.log('接收新线索');
        console.log(event);
        if (event.type == "0") {
            if (event.msgType == "normal") {
                window.open("/saas/clue/myclue/detailclue;id=" + event.data.clueCode);
            } else if (event.msgType == "time") {
                this.saasService.acceptClue(event).then(data => {
                    if (data.result) {
                        this.storage.messageService.emit({ severity: 'success', detail: "操作成功！" });
                    } else {
                        this.storage.messageService.emit({ severity: 'success', detail: data.msg });
                    }
                }
                );
            }
        }
        if (event.type == "4") {
            console.log(event);
            if (event.auditedStatus == "2") {
                //申请
                if (event.facilitatorType == '1') {
                    this.router.navigate(['/saas/service/serviceAudit/create']);
                }
                //修改
                if (event.facilitatorType == '2') {
                    if ('/saas/service/serviceManage/detail' == this.router.url) {
                        window.location.reload();
                    } else {
                        this.router.navigate(['/saas/service/serviceManage/detail']);
                    }
                }
            } else if (event.auditedStatus == "1") {
                if (event.facilitatorType == '1') {
                    this.router.navigate(['/saas/service/serviceMarketMargin/marketmargin/add']);
                }
                if (event.facilitatorType == '2') {
                    this.router.navigate(['/saas/service/serviceManage/detail']);
                }
            }

        }
        if (event.type == "5") {
            console.log(event);
            if (event.marginAuditStatus == "2") {
                //申请
                if (event.isDelivery == true) {
                    this.router.navigate(['/saas/service/serviceMarketMargin/marketmargin/edit/' + event.orderNo]);
                }
                //修改

                if (event.isDelivery == false) {
                    if ('/saas/service/serviceManage/detail' == this.router.url) {
                        window.location.reload();
                    } else {
                        this.router.navigateByUrl('/saas/service/serviceManage/detail');
                    }

                }
            } else if (event.marginAuditStatus == "1") {
                //创建成功页面

                //申请
                if (event.isDelivery == true) {
                    //window.location.reload();
                    this.router.navigateByUrl('/saas/service/serviceManage/detail?type=1');
                } else {
                    //修改
                    if (event.isDelivery == false) {
                        if ('/saas/service/serviceManage/detail' == this.router.url) {
                            window.location.reload();
                        } else {
                            this.router.navigate(['/saas/service/serviceManage/detail']);
                        }

                    }
                }

            }

        }
    }

    /* 链接socket  -----start*/


    creatWs(code) {

        if (!code) { return }

        this.ws = new $WebSocket("ws://" + environment.wsUrl + "ws?code=" + code);

        this.ws.onMessage(
            (msg: MessageEvent) => {
                let data = JSON.parse(msg.data);
                if (data.type == "0") {
                    this.newClue(msg.data);
                    this.socket.onMessage.emit(msg.data)
                } else if (data.type == "4") {
                    this.newClue2(msg.data)
                    this.socket.onMessage.emit(msg.data)
                } else if (data.type == "5") {
                    this.newClue3(msg.data)
                    this.socket.onMessage.emit(msg.data)
                }
            },
            { autoApply: false }
        );

        this.ws.onOpen(msg => this.socket.onOpen.emit());

        this.ws.onClose(msg => { this.socket.onClose.emit(); console.log(msg) });

        this.ws.onError(msg => this.socket.onError.emit());

    }


    /* 链接socket  -----end*/

}
